#include "codec.h"
#include <QDebug>

// 序列化 Message -> QByteArray
Codec::Codec(Message *msg)
{
    reLoad(msg);
}

// 反序列化 QByteArray -> Message
Codec::Codec(QByteArray msg)
{
    reLoad(msg);
}

// 数据编码 Message -> QByteArray
QByteArray Codec::encodeMsg()
{
    std::string out;
    m_obj.SerializeToString(&out);
    return QByteArray::fromStdString(out);
}

// 数据解码 QByteArray -> Message
QSharedPointer<Message> Codec::decodeMsg()
{
    std::string data = m_msg.toStdString();
    m_obj.ParseFromString(data);
    auto ptr = QSharedPointer<Message>(new Message());
    ptr->userName = QByteArray::fromStdString(m_obj.username());
    ptr->roomName = QByteArray::fromStdString(m_obj.roomname());
    ptr->data1 = QByteArray::fromStdString(m_obj.data1());
    ptr->data2 = QByteArray::fromStdString(m_obj.data2());
    ptr->data3 = QByteArray::fromStdString(m_obj.data3());
    ptr->reqcode = m_obj.reqcode();
    ptr->rescode = m_obj.rescode();

    return ptr;
}

// 重新加载数据
void Codec::reLoad(QByteArray msg)
{
    m_msg = msg;
}

void Codec::reLoad(Message *msg)
{
    m_obj.set_username(msg->userName.toStdString());
    m_obj.set_roomname(msg->roomName.toStdString());
    m_obj.set_data1(msg->data1.toStdString());
    m_obj.set_data2(msg->data2.toStdString());
    m_obj.set_data3(msg->data3.toStdString());
    m_obj.set_reqcode(msg->reqcode);
    m_obj.set_rescode(msg->rescode);
}

